<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改班级信息')" />
    <th:block th:include="include :: bootstrap-select-css" />
    <th:block th:include="include :: summernote-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-classInfo-edit" th:object="${classInfo}">
            <div class="tabs-container">
                <ul class="nav nav-tabs">
                    <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">基本信息</a>
                    </li>
                    <li class=""><a id="question_tab" data-toggle="tab" href="#tab-2" aria-expanded="false">名言警句</a>
                    </li>

                </ul>
                <div class="tab-content">
                    <div id="tab-1" class="tab-pane active">
                        <div class="panel-body">
                            <input name="id" th:field="*{id}" type="hidden">
                            <div class="form-group">
                                <label class="col-sm-3 control-label">班级名称：</label>
                                <div class="col-sm-8">
                                    <input name="className" th:field="*{className}" class="form-control" type="text">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label is-required">班主任：</label>
                                <div class="col-sm-8">
                                    <select name="teacherId"  class="form-control m-b" th:with="type=${@teacher.getTeacherList()}" required th:field="*{teacherId}">
                                        <option th:each="teacher : ${type}" th:text="${teacher.userName}" th:value="${teacher.userId}"  ></option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label is-required">年级：</label>
                                <div class="col-sm-8">
                                    <input id="gradeName" name="gradeName"  type="hidden">
                                    <select class='form-control selectpicker' data-live-search="false" id='gradeId' name='gradeId' required data-th-grade-id="*{gradeId}">
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label is-required">所在教室：</label>
                                <div class="col-sm-8">
                                    <select class='form-control'  name="roomId" th:with="type=${@roomInfo.getRoomListDict()}" required  th:field="*{roomId}">
                                        <option th:each="dict : ${type}" th:text="${dict.roomName}" th:value="${dict.id}"  ></option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">班级风采：</label>
                                <div class="col-sm-8">
                                    <div class="ibox-content no-padding">
                                        <input id="description" name="description" th:field="*{description}" type="hidden">
                                        <div class="summernote" id="content" required>

                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">班级照片：</label>
                                <div class="col-sm-8">
                                    <input type="hidden"  name="img" id="img_url" th:value="*{img}">
                                    <div class="file-loading">
                                        <input type="file"  name="file" id="img">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-offset-5 col-sm-10">
                                    <button type="button" class="btn btn-sm btn-primary" onclick="saveClassInfo()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                                </div>
                            </div>
                        </div>
                    </div>

                    <!--名言警句设置-->
                    <div id="tab-2" class="tab-pane">
                        <div class="panel-body">
                            <div class="panel-heading">
                                <a class="btn btn-success" href="javascript:void(0)" onclick="addContent()">添加</a>
                            </div>

                            <div id="wisdomContent">
                                <div class="form-group wisdomContent" th:each="wisdom:${classInfo.wisdomList}">
                                    <label class="col-sm-2 control-label">序号：</label>
                                    <div class="col-sm-1">
                                        <input name="sortNo" class="form-control sortNo" type="number" th:value="${wisdom.sortNo}">
                                    </div>

                                    <label class="col-sm-1 control-label">内容：</label>

                                    <div class="col-sm-5">
                                        <textarea name="content" class="form-control content"  th:text="${wisdom.content}" style="width: 310px;" rows="5" maxlength="80">
                                            </textarea>
                                    </div>
                                    <div class="col-sm-1">
                                        <a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeContent(this)">删除</a>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-offset-5 col-sm-10">
                                    <button type="button" class="btn btn-sm btn-primary" onclick="saveWisdom()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </form>

    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-select-js" />
    <th:block th:include="include :: summernote-js" />
    <th:block th:include="include :: bootstrap-fileinput-js" />
    <script type="text/javascript">
        var prefix = ctx + "school/classInfo";
        var List = new Array();
        $("#form-classInfo-edit").validate({
            focusCleanup: true
        });
        $(document).ready(function () {
            $('.summernote').summernote({
                lang: 'zh-CN',
                height: 100,
                followingToolbar: false,
                callbacks: {
                    onImageUpload: function (files) {
                        sendFile(files[0], this);
                    }
                }
            });
            var content = $("#description").val();
            $('#content').summernote('code', content);
        });
        // 上传文件
        function sendFile(file, obj) {
            var data = new FormData();
            data.append("file", file);
            $.ajax({
                type: "POST",
                url: ctx + "common/upload",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $(obj).summernote('editor.insertImage', result.url, result.fileName);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function(error) {
                    $.modal.alertWarning("图片上传失败。");
                }
            });
        }
        function saveClassInfo() {
            if ($.validate.form()) {
                var sHTML = $('.summernote').summernote('code');
                $("#description").val(sHTML);
                for (let i = 0; i < List.length ; i++) {
                    var url = $("#img_url").val();
                    if(url == null || url == undefined){
                        url=List[i].url;
                    }else {
                        url = url+","+List[i].url;
                    }
                    $("#img_url").val(url);
                }
                $.operate.save(prefix + "/edit", $('#form-classInfo-edit').serialize());
            }
        }

        function saveWisdom() {
            var data = $(".wisdomContent")
            var json = {};
            json["classId"] = $("#id").val();
            for (let i = 0; i < data.length ; i++) {
               var wisdom = {};
               var sortNo = $(data[i]).find('.sortNo').val();
               var content = $(data[i]).find('.content').val();
               if(sortNo.length == 0 || content.length == 0){
                   $.modal.alertWarning("请填写完整内容!");
               }
                json["wisdomList["+i+"].sortNo"]=sortNo;
                json["wisdomList["+i+"].content"]=content;
                json["wisdomList["+i+"].classId"]=$("#id").val();
            }
            $.operate.save(prefix + "/saveWisdom", json);
        }

        $(document).ready(function() {

            var imgData = {};
            var config = [];
            if($("#img_url").val() != null && $("#img_url").val() != undefined){
                imgData = $("#img_url").val().split(",");
                for (let i = 0; i < imgData.length; i++) {
                    var data = {};
                    data["caption"] = "transport-"+i+".jpg";
                    data["size"] = 329892;
                    data["width"] = "120px";
                    data["key"] = imgData[i];
                    data["url"] = 'deletePic';
                    config.push(data);
                }
            }
            $("#img").fileinput({
                'theme': 'explorer-fas',
                'uploadUrl': '/common/upload',
                //'deleteUrl': deleteImg(),
                'overwriteInitial': false,
                'maxFileCount':5,
                'elCaptionText':'sss',
                'showUpload':false,
                'initialPreviewAsData': true,
                'initialPreview': imgData,
                'initialPreviewConfig': config

            }).on("filebatchselected", function(event, files) { // 选择文件后回调
                $("#img").fileinput("upload");
            }).on("fileuploaded", function(event, data, previewId, index) { // 上传成功回调
                if(data.response.code == 0){
                    List.push({ "url": data.response.url, "previewId": previewId })
                }
            }).on('filepredelete', function(event, key, jqXHR, data) {
                 var url = $("#img_url").val().split(",");
                 url.splice(jQuery.inArray(key,url),1);
                 $("#img_url").val(url.toString());
            }).on("filesuccessremove", function (event, data, previewId, index) {
                 List.splice(previewId,1);
            });

            $.ajax({
                type: "post",
                url: ctx + "school/grade/getGradeList",
                async: false,
                dataType: "json",
                success: function (res) {
                    if (null != res) {
                        var html = '';
                        var selectedId = $("#gradeId").attr('grade-id');
                        Object.keys(res).forEach(function(key){

                            if(selectedId == res[key].id){
                                html += '<option selected = "selected" value="' + res[key].id + '" data-tokens="'+ res[key].gradeName+'">' + res[key].gradeName+ '</option>';
                            }else{
                                html += '<option  value="' + res[key].id + '" data-tokens="'+ res[key].gradeName+'">' + res[key].gradeName+ '</option>';
                            }


                        });
                        $("#gradeId").html(html);
                        //必须加，刷新select
                        $("#gradeId").selectpicker('refresh');
                    }
                }
            });
        })

        function addContent() {
            if($('.wisdomContent').length ==10){
                $.modal.alertWarning("最多添加10条名言警句!");
                return;
            }
            var content = ' <div class="form-group wisdomContent">\n' +
                '                                    <label class="col-sm-2 control-label">序号：</label>\n' +
                '\n' +
                '                                    <div class="col-sm-1">\n' +
                '                                        <input name="content sortNo" class="form-control sortNo" type="number">\n' +
                '                                    </div>\n' +
                '\n' +
                '                                    <label class="col-sm-1 control-label">内容：</label>\n' +
                '\n' +
                '                                    <div class="col-sm-5">\n' +
                '                                        <textarea name="content" class="form-control content" style="width: 310px;" rows="5" maxlength="80"></textarea>\n' +
                '                                    </div>\n' +
                '                                    <div class="col-sm-1">\n' +
                '                                        <a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeContent(this)">删除</a>\n' +
                '                                    </div>\n' +
                '                                </div>';

            $("#wisdomContent").append(content);
        }

        function removeContent(obj) {
            $(obj).parents('.wisdomContent').remove();
        }
    </script>
</body>
</html>